<template>
	<view class="login">
		<view class="avatar">
			<uni-icons type="contact-filled" size="108" class="user-avatar" color="#AFAFAF"></uni-icons>
		</view>
		<view class="login-btn">
			<button type="warn" class="one-key-login" @click="oneKeyLogin">一键登录</button>
		</view>
		<text class="tip">登录后尽享更多权益</text>
	</view>
</template>

<script>
	import {
		mapMutations
	} from 'vuex'

	import {
		doWXLogin
	} from '../../service/user_api.js'

	export default {
		name: "Login",
		data() {
			return {

			};
		},
		methods: {
			...mapMutations('user', ['updateUserInfo', 'updateToken']),
			oneKeyLogin() {
				const _this = this
				uni.getUserProfile({
					desc: '获取用户信息用于构建登录界面',
					success(e) {
						_this.updateUserInfo(e.userInfo)
						_this.getToken(e)
					},
					fail() {
						uni.$showMsg('用户未授权')
					}
				})
			},
			async getToken(loginInfo) {
				const [err, res] = await uni.login().catch(err => err)

				if (err || res.errMsg !== 'login:ok') return uni.$showMsg('登录失败！')

				const query = {
					code: res.code,
					encryptedData: loginInfo.encryptedData,
					iv: loginInfo.iv,
					rawData: loginInfo.rawData,
					signature: loginInfo.signature
				}

				const loginResult = await doWXLogin(query)
				if (loginResult.meta.status === 400) {
					const token = 'aridiculousboy!@#24'
					this.updateToken(token)
					uni.$showMsg('登录成功')
				}
			}
		}
	}
</script>

<style lang="scss">
	.login {
		display: flex;
		height: 100vh;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		background-color: rgb(246, 249, 248);
		transform: translateY(-16%);

		.login-btn {
			width: 100%;
		}

		.one-key-login {
			width: 82%;
			margin-top: 12rpx;
			height: 84rpx;
			border-radius: 96rpx;
			font-size: 32rpx;
		}

		.tip {
			margin-top: 16rpx;
			font-size: 22rpx;
			color: gray;
		}
	}
</style>
